package com.huatai.exchange.utils;

import com.faneui.common.exception.BusinessException;
import com.faneui.common.utils.CloseUtils;
import com.faneui.common.utils.IOUtils;
import com.faneui.common.utils.ListUtils;
import com.faneui.dbf.utils.DBFUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.huatai.exchange.facade.Contents;
import com.linuxense.javadbf.DBFField;
import de.schlichtherle.util.zip.ZipEntry;
import de.schlichtherle.util.zip.ZipOutputStream;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

public class FileDealUtils {

    private static final Logger logger = LoggerFactory.getLogger(FileDealUtils.class);

    public static String formatStr(String str,  Map<String, Object> resvMap) throws BusinessException{
        return formatStr(str,null,resvMap) ;
    }

    public static String formatStr(String str, Map<String, Object> excDataFileMap, Map<String, Object> resvMap) throws BusinessException {
        if (StringUtils.isBlank(str)) {
            return str;
        }
        String yyyyMMdd = (String) resvMap.get(Contents.FIELD_YYYYMMDD);

        String tmpStr = str;
        while (tmpStr.contains("${") && tmpStr.contains("}")) {
            Integer startNum = tmpStr.indexOf("${") + 2;
            Integer endNum = tmpStr.indexOf("}");
            String field = tmpStr.substring(startNum, endNum);
            logger.info("field:" + field);
            String value = (String) resvMap.get(field);
            if (StringUtils.isBlank(value) && excDataFileMap != null) {
                value = (String) excDataFileMap.get(field);
            }
            if (StringUtils.isBlank(value)) {
                if (Contents.FIELD_ZTMC.equals(field)) {
                    String ztmc = (String) resvMap.get(Contents.FIELD_ZTMC);
                    if (StringUtils.isBlank(ztmc))
                        throw new BusinessException("账套名称必须标记");
                    value = ztmc;
                } else if (Contents.FIELD_YYYY_MM_DD.equals(field)) {
                    if (StringUtils.isBlank(yyyyMMdd))
                        throw new BusinessException("日期必须标记");
                    value = yyyyMMdd.substring(0, 4) + "-" + yyyyMMdd.substring(4, 6) + "-" + yyyyMMdd.substring(6);
                } else if (Contents.FIELD_YYMMDD.equals(field)) {
                    if (StringUtils.isBlank(yyyyMMdd))
                        throw new BusinessException("日期必须标记");
                    value = yyyyMMdd.substring(2);
                } else if (Contents.FIELD_YYMM.equals(field)) {
                    if (StringUtils.isBlank(yyyyMMdd))
                        throw new BusinessException("日期必须标记");
                    value = yyyyMMdd.substring(2, 6);
                } else if (Contents.FIELD_YYYY.equals(field)) {
                    if (StringUtils.isBlank(yyyyMMdd))
                        throw new BusinessException("日期必须标记");
                    value = yyyyMMdd.substring(0, 4);
                } else if (Contents.FIELD_YYYYMM.equals(field)) {
                    if (StringUtils.isBlank(yyyyMMdd))
                        throw new BusinessException("日期必须标记");
                    value = yyyyMMdd.substring(0, 6);
                } else if (Contents.FIELD_MM_DD.equals(field)) {
                    if (StringUtils.isBlank(yyyyMMdd))
                        throw new BusinessException("日期必须标记");
                    value = yyyyMMdd.substring(4, 6) + "-" + yyyyMMdd.substring(6);
                } else if (Contents.FIELD_MMDD.equals(field)) {
                    if (StringUtils.isBlank(yyyyMMdd))
                        throw new BusinessException("日期必须标记");
                    value = yyyyMMdd.substring(4);
                } else if (Contents.FIELD_MCDD.equals(field)) {
                    value = transferMonth(yyyyMMdd.substring(4, 6)) + yyyyMMdd.substring(6, 8);
                } else {
                    return tmpStr;
                }
                resvMap.put(field, value);
            }
            String oldStr = "${" + field + "}";
            tmpStr = tmpStr.replace(oldStr, value);
        }
        return tmpStr;
    }

    public static void main(String[] args) throws Exception{
        String str = "http://10.248.26.70:10010/reporttemplate/export?templateName=f625b281-f64a-4ed7-9f3d-0fa879754ffd.cpt&paramJson=%7B%22%E5%9F%BA%E9%87%91%E4%BB%A3%E7%A0%81%22%3A%22%${FUNDCODE}%22%2C%22%E6%97%B6%E9%97%B4%22%3A%222${YYYY-MM-DD}%22%7D" ;
        //System.out.println(URLDecoder.decode(str,"UTF-8"));
        Map<String,Object> resvMap = Maps.newHashMap() ;
        resvMap.put("FUNDCODE","990112") ;
        resvMap.put("YYYY-MM-DD","990112") ;
        System.out.println(formatStr(str,resvMap,resvMap));
    }

    public static void zip(ZipOutputStream zos,File tmpFile ,SmbFile smbFile) throws BusinessException {
        InputStream is = null;
        OutputStream os = null;
        InputStream nis = null;
        try {
            is = new SmbFileInputStream(smbFile);
            os = new FileOutputStream(tmpFile) ;
            IOUtils.download(os, is);
            os.close();
            nis = new FileInputStream(tmpFile) ;
            zos.putNextEntry(new ZipEntry(smbFile.getName()));
            IOUtils.download(zos, nis);
        } catch (Exception ex) {
            BusinessException.throwBusinessException(ex);
        } finally {
            CloseUtils.safeClose(os,is,nis);
        }
    }

//    public static void main(String[] args) throws Exception {
//        String smbDirUrl = "smb://10.248.60.100/信息技术部/制度/" ;
//        String username = "HTAM\\obss" ;
//        String password = "Huatai@000" ;
//        NtlmPasswordAuthentication auth  = SmbFileUtils.createAuth(smbDirUrl,username,password);
//        SmbFile smbDir = new SmbFile(smbDirUrl,auth) ;
//        File f =new File("c:/tmp/test.zip");
//        OutputStream os = new FileOutputStream(f) ;
//        ZipOutputStream zos = new ZipOutputStream(os, ZipUtil.charset) ;
//        String[] fileNames = smbDir.list() ;
//        for(String smbFileName:fileNames){
//            zip(zos,new SmbFile(smbFileName,auth));
//        }
//        zos.close();
//        os.close();
//    }

    public static void createDBFFile(DBFField[] dbfFields, String filePath, List<Map<String, Object>> result) throws BusinessException {
        OutputStream os = null;
        try {
            os = new FileOutputStream(filePath);
            List<Object[]> objectsList = Lists.newArrayList();
            for (Map<String, Object> dataMap : result) {
                List<Object> objects = Lists.newArrayList();
                for (DBFField field : dbfFields) {
                    objects.add(dataMap.get(field.getName().toUpperCase()));
                }
                objectsList.add(objects.toArray());
            }
            DBFUtils.addDBFRecord(os, dbfFields, objectsList);
        } catch (Exception ex) {
            BusinessException.throwBusinessException(ex);
        } finally {
            CloseUtils.safeClose(os);
        }
    }

    public static Map<String, List<Map<String, Object>>> convert(List<Map<String, Object>> result, String field) {
        Map<String, List<Map<String, Object>>> dataListMap = Maps.newHashMap();
        for (Map<String, Object> map : result) {
            String value = map.get(field).toString();
            List<Map<String, Object>> dataList = dataListMap.get(value);
            if (ListUtils.isEmpty(dataList)) {
                dataList = Lists.newArrayList();
                dataListMap.put(value, dataList);
            }
            dataList.add(map);
        }
        return dataListMap;
    }

    public static String getFirstField(String value) throws BusinessException {
        if (value.contains("${") && value.contains("}")) {
            Integer startNum = value.indexOf("${") + 2;
            Integer endNum = value.indexOf("}");
            return value.substring(startNum, endNum);
        }
        return null;
    }

    public static String transferMonth(String mm) {
        String mc = mm;
        if ("10".equals(mm)) {
            mc = "a";
        } else if ("11".equals(mc)) {
            mc = "b";
        } else if ("12".equals(mc)) {
            mc = "c";
        } else {
            mc.substring(1);
        }
        return mc;
    }
}
